package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.os.Environment;

import com.StarMicronics.StarIOSDK.logic.Config;
import com.StarMicronics.StarIOSDK.logic.MyApplication;

/**
 * 文件保存在系统或SDCard，设置："Config.bFileOperationInSDCard;"+
 * "Config.fileOperationInSDCardPath;" 注：调试时，建议保存在SDCard，因为真机系统文件需要root才能看到；
 */
public class Util_File {

	private static String appFilePathInSDCard = null;// 当前应用所有文件存储的SDCard绝对路径（前提：如果文件系统定在SD卡，否则null）

	// /mnt/sdcard

	/**
	 * 注：务必在MyApplication里调用
	 * 
	 * 校对：如config设置文件保存在SD卡，但SD卡不存在情况下，强置bFileOperationInSDCard = false;
	 */
	public static void checkFileOperationInSDCard() {
		if (Config.bFileOperationInSDCard && !isSDCardExit()) {
			Config.bFileOperationInSDCard = false;
		}
		if (Config.bFileOperationInSDCard && appFilePathInSDCard == null) {
			// 组织好路径
			// File file = Environment.getExternalStorageDirectory();// SD card
			// 的root
			// path
			appFilePathInSDCard = Config.fileOperationInSDCardPath;
			debug("appFilePathInSDCard:" + appFilePathInSDCard);
		}
	}

	/**
	 * 检查SD卡是否存在
	 */
	public static boolean isSDCardExit() {
		return Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
	}

	/**
	 * 手机系统文件：【data】
	 * 
	 * @param fileName
	 *            ：文件名，并非路径
	 * @param MODE
	 * @return
	 */
	private static FileOutputStream getStreamFileOutput(String fileName, int MODE) {
		try {
			return MyApplication.getInstance().openFileOutput(fileName, MODE);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 手机系统文件：【data】
	 * 
	 * @param fileName
	 *            ：文件名，并非路径
	 * @return
	 */
	private static FileInputStream getSystemFileInputStream(String fileName) {
		try {
			return MyApplication.getInstance().openFileInput(fileName);
		} catch (Exception e) {
			return null;
		}
	}

	private static File getCurProjectFileInSDCard(String fileName) {

		try {
			File path = new File(appFilePathInSDCard);
			if (!path.exists()) {
				path.mkdirs();
			}

			File file = new File(Util_G.strAddStr(appFilePathInSDCard, fileName));
			if (!file.exists()) {
				file.createNewFile();
			}
			return file;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 手机SD卡文件：【SD CARD】
	 * 
	 * @param fileName
	 *            ：文件名，并非路径
	 * @param MODE
	 * @return
	 */
	private static FileOutputStream getSDCardFileOutput(String fileName, int MODE) {
		try {
			return new FileOutputStream(getCurProjectFileInSDCard(fileName), MODE == Context.MODE_APPEND ? true : false);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 手机SD卡文件：【SD CARD】
	 * 
	 * @param fileName
	 *            ：文件名，并非路径
	 * @return
	 */
	private static FileInputStream getSDCardFileInputStream(String fileName) {

		try {
			return new FileInputStream(getCurProjectFileInSDCard(fileName));
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * @param data
	 *            : byte[]
	 * @param fileName
	 *            : 文件名称，并不是文件路径，不能包含路径分隔符“/” ，如果文件不存在，Android
	 *            会自动创建它。创建的文件保存在/data/data/<package name>/files目录，真机需要root才能看到；
	 * @param MODE
	 *            : Context.MODE_PRIVATE = 0 Context.MODE_APPEND = 32768 :
	 *            系统、SDCard 都适用； Context.MODE_WORLD_READABLE = 1
	 *            Context.MODE_WORLD_WRITEABLE = 2
	 */
	public static boolean writeFile(byte[] data, String fileName, int MODE) {

		if (data == null)
			return false;
		FileOutputStream outStream = null;
		try {
			if (Config.bFileOperationInSDCard) {
				outStream = getSDCardFileOutput(fileName, MODE);
			}
			outStream.write(data);
		} catch (Exception e) {
			return false;
		} finally {
			try {
				if (outStream != null)
					outStream.close();
			} catch (Exception e) {
			}
		}
		return true;
	}

	public static boolean writeFileByPath(byte[] data, String fileName_Path, int MODE) {

		if (data == null)
			return false;
		FileOutputStream outStream = null;
		try {
			File file = new File(fileName_Path);
			// System.out.println("fileName_Path-->>"+fileName_Path);
			if (!file.exists()) {
				file.createNewFile();
			}
			outStream = new FileOutputStream(file, MODE == Context.MODE_APPEND ? true : false);
			outStream.write(data);
		} catch (Exception e) {
			return false;
		} finally {
			try {
				if (outStream != null)
					outStream.close();
			} catch (Exception e) {
			}
		}
		return true;
	}

	/**
	 * @param data
	 *            : String
	 * @param fileName
	 *            : 文件名称，不能包含路径分隔符“/” ，如果文件不存在，Android
	 *            会自动创建它。创建的文件保存在/data/data/<package name>/files目录
	 * @param MODE
	 *            : Context.MODE_PRIVATE = 0 Context.MODE_APPEND = 32768
	 *            Context.MODE_WORLD_READABLE = 1 Context.MODE_WORLD_WRITEABLE =
	 *            2
	 */
	public static boolean writeFile(String data, String fileName, int MODE) {
		// Util_G.debug("writeFile(), fileName="+fileName+", "+"content="+data);
		return writeFile(Util_G.utf8Encode(data), fileName, MODE);
	}

	/**
	 * @param fileName
	 *            ：文件名，并非路径
	 * @return
	 */
	public static byte[] readFile(String fileName) {

		byte[] d = null;
		FileInputStream inStream = null;
		try {
			if (Config.bFileOperationInSDCard) {
				inStream = getSDCardFileInputStream(fileName);
			} else {
				inStream = getSystemFileInputStream(fileName);
			}

			d = Util_G.getByteArrayFromInputstream(inStream, -1);
		} catch (Exception e) {
			return null;
		} finally {
			try {
				if (inStream != null)
					inStream.close();
			} catch (Exception e) {
			}
		}
		return d;
	}

	/**
	 * UTF-8格式
	 * 
	 * @param fileName
	 *            ：文件名，并非路径
	 * @return
	 */
	public static String readFile2String(String fileName) {
		return Util_G.utf8Decode(readFile(fileName));
	}

	private static void debug(String str) {
		System.out.println(str);
	}

	/**
	 * @param fileName
	 *            ：文件名，并非路径
	 * @return
	 */
	public static byte[] readImage(String fileName, int imgLen) {

		byte[] d = null;
		FileInputStream inStream = null;
		try {
			// if(Config.bImagesOperationInSDCard){
			inStream = new FileInputStream(fileName);
			;
			// }else{
			// inStream = getSystemFileInputStream(fileName);
			// }
			d = Util_G.getByteArrayFromInputstream(inStream, imgLen + 100);
		} catch (Exception e) {
			return null;
		} finally {
			try {
				if (inStream != null)
					inStream.close();
			} catch (Exception e) {
			}
		}
		return d;
	}

	public static void deletefile(String delpath) throws FileNotFoundException, IOException {
		try {
			File file = new File(delpath);
			if (!file.isDirectory()) {
				file.delete();
			} else if (file.isDirectory()) {
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					File delfile = new File(delpath + "\\ " + filelist[i]);
					if (!delfile.isDirectory())
						delfile.delete();
					else if (delfile.isDirectory())
						deletefile(delpath + "\\ " + filelist[i]);
				}
				file.delete();
			}
		} catch (FileNotFoundException e) {
		}
	}

	/**
	 * 删除文件夹
	 * 
	 * @param filePathAndName
	 *            String 文件夹路径及名称 如c:/fqf
	 * @param fileContent
	 *            String
	 * @return boolean
	 */
	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹

		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	/**
	 * 删除文件夹里面的所有文件
	 * 
	 * @param path
	 *            String 文件夹路径 如 c:/fqf
	 */
	public static void delAllFile(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return;
		}
		if (!file.isDirectory()) {
			return;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
			}
		}
	}

}
